package wli.web.servlet;

import java.io.IOException;

import java.io.PrintWriter;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import wli.hibernate.Roles;
import wli.hibernate.Users;
import wli.hibernate.db.Category;
import wli.hibernate.db.ForumThread;
import wli.hibernate.db.Subject;
import wli.hibernate.util.HibernateUtil;
import wli.java.security.util.Md5Encryption;
import wli.web.util.TextToHtml;
import wli.hibernate.util.*;

/**
 * Servlet implementation class VMainServlet
 */
@WebServlet("/vmain")
public class VMainServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public VMainServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) {
		try {
			PrintWriter out = response.getWriter();
			HttpSession session = request.getSession(true);

			String vcname = request.getParameter("vcname");
			String vcid = request.getParameter("vcid");
			String vsname = request.getParameter("vsname");
			String vsid = request.getParameter("vsid");
			String vcsname = request.getParameter("vcsname");
			String vcsid = request.getParameter("vcsid");
			String add_thread = request.getParameter("avcsid");
			String pid = request.getParameter("pid");
			String position = request.getParameter("position");
			String vmaid = request.getParameter("vmaid");
			String edit_thread = request.getParameter("edit_thread");

			String web_host = "http://192.168.1.13";

			if (vcid != null && vcname != null) {
				out.println("<h2>Category Description:"
						+ request.getAttribute("Category-Description")
						+ "</h2>");
			}

			if (vcid == null && vsid == null && vcsid == null && vmaid == null
					&& request.getParameter("new_category") == null
					&& request.getParameter("add_category") == null) {
				if (request.getRemoteUser() == null) {
					out.println("<img src=" + web_host + "/image/2.JPG>");
					System.out
							.println("<img src=" + web_host + "/image/2.JPG>");
				}
				if (request.getRemoteUser() != null
						&& (request.getRemoteUser().equals("eli") || request
								.getRemoteUser().equals("fli"))) {
					out.println("<img src=" + web_host + "/image/1.JPG>");
					System.out
							.println("<img src=" + web_host + "/image/2.JPG>");
				}
			}

			/*
			 * Create user
			 */
			boolean create_user = false;

			if (vmaid != null && vmaid.equals("1")) {
				create_user = true;
			}

			if (create_user) {

				org.hibernate.Session hhsession = HibernateUtil
						.getSessionFactory().openSession();
				Transaction ttransaction = hhsession.beginTransaction();
				try {
					Users users = new Users();
					Set<Roles> role_set = new HashSet<Roles>();
					Roles usrl6 = new Roles();
					usrl6.setRoleName("members");
					role_set.add(usrl6);
					users.setUserName("kli");
					users.setPassWord(Md5Encryption.MD5("li0578"));
					users.setUserRoles(role_set);

					System.out.println("Test add user only....");
					hhsession = HibernateUtil.getSessionFactory().openSession();
					ttransaction = hhsession.beginTransaction();

					System.out.println("User [" + hhsession.save(users)
							+ "] Saved.");
					ttransaction.commit();
					// hhsession.close();
				} catch (HibernateException e) {
					ttransaction.rollback();
					e.printStackTrace();
				} catch (NoSuchAlgorithmException e) {
					e.printStackTrace();
				} finally {
					// hhsession.close();
				}

				out.println("create user...");
			}

			/**
			 * Edit Category
			 */

			if (request.getRemoteUser() != null) {

				if (request.getParameter("Edit") != null
						|| request.getParameter("delete") != null) {
					ArrayList alist = (ArrayList) getCategoryList(request
							.getRemoteUser());

					out.println("<form><table border=1 bgcolor=#EFEFEF>");
					Iterator<Category> its = alist.iterator();
					Category cat = null;
					while (its.hasNext()) {
						cat = (Category) its.next();
						out.println("<tr><td><input type=button value="
								+ cat.getName() + "></td>");

						if (hasSubject(cat.getCategory_id())) {
							out.println("<td>you can't delete</td>");
							out.println("<td><input type=button onClick=\"location.href='?vcid="
									+ cat.getCategory_id()
									+ "&vcname="
									+ cat.getName()
									+ "&delete=0'\" value='Delete'></td>");
						} else {
							out.println("<td>ok to delete</td>");
							out.println("<td><input type=button onClick=\"location.href='?vcid="
									+ cat.getCategory_id()
									+ "&vcname="
									+ cat.getName()
									+ "&delete=1'\" value='Delete'></td>");
						}
						out.println("</tr>");
					}
					out.println("</table></form>");

				}
			}

			/**
			 * Display Open Thread Link
			 */

			if (vcid != null && vsid != null && vcsid != null) {
				out.println("<a href=?vcsid="
						+ vcsid
						+ "&vcid="
						+ vcid
						+ "&vsid="
						+ vsid
						+ "&avcsid=3&pid=0&position=0>[Open a Thread]</a>[vcid="
						+ vcid + "] vsid=" + vsid + "] [vcsid=" + vcsid
						+ "]<BR><HR>");
			}

			/**
			 * Add thread
			 */

			if (add_thread != null) {
				if (add_thread.equals("3")) {

					if (vcid != null && vsid != null && vcsid != null
							&& pid != null && position != null) {

						String submit_thread = request
								.getParameter("submit_thread");
						System.out
								.println("Main;;;AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
						if (submit_thread == null && edit_thread == null) {
							System.out
									.println("Main;;;BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB");
							ForumThread fthread = getSingleForumThread(vsid,
									vcsid);

							session.setAttribute(vcsid,
									System.currentTimeMillis());
							out.println("<table border=0 width=90% bgcolor=#EFEFEF>");
							out.println("<tr><td bgcolor=#A596CB><b>"
									+ fthread.getTitle()
									+ "</b></td><td bgcolor=#A596CB>---By::&nbsp;&nbsp;<I>"
									+ fthread.getOwner()
									+ "</I></td><td bgcolor=#A596CB>"
									+ fthread.getDate()
									+ "</td><td bgcolor=#A596CB align=center>"

									+ "<a href=?edit_thread=true&vcid="
									+ vcsid.substring(0, vcsid.indexOf('-'))
									+ "&vcsid=" + vcsid + "&vsid="
									+ fthread.getId() + "&avcsid=3&pid="
									+ fthread.getParent_id() + "&position="
									+ fthread.getPosition() + ">" + "Edit</a>"

									// + "<a href=?vcid=" + fthread.getId()
									// + "&vcsid=" + fthread.getBoard_id()
									// + "&vsid=" + fthread.getParent_id()
									// + "&avcsid=3&pid="+ forthr.getId() +
									// "&position="
									// + forthr.getPosition() + ">"
									// + forthr.getTitle()
									// + ">[Edit]</a>"
									+ "</td></tr>");

							if (fthread.getPosition() != null) {

								if (fthread.getLinked_url() != null) {

									out.println("<tr><td colspan=3>"
											+ fthread.getLinked_url()
											+ "</td></tr>");
									if (fthread.getLinked_url() != null
											&& fthread.getLinked_url()
													.toLowerCase()
													.startsWith("http")) {

										System.out.println("Linked_URL is:"
												+ fthread.getLinked_url());
										out.println("<tr><td colspan=3><iframe src="
												+ fthread.getLinked_url()
												+ " width=100% height=500>");
										out.println("<p>Your browser does not support iframes.</p>");
										out.println("</iframe></td></tr>");
									}
								}
								if (fthread.getMessage() != null) {
									out.println("<tr><td colspan=3>"
											+ fthread.getMessage()
											+ "</td></tr>");
								}
							}
							out.println("</table><BR><BR>");

							if (edit_thread == null) {
								/**
								 * This is the form for rerply thread
								 */
								out.println("<form action=>");
								out.println("<table bgcolor=#DEDEDE width=90%>");
								out.println("<tr><td colspan=2 bgcolor=#A596CB><b>Reply to this thread</b></td></tr>");
								out.println("<tr><td>Title</td>");
								out.println("<td>");

								out.println("<input type=text name=file_title size =150 maxsize=200");
								out.println("value=\'" + fthread.getTitle()
										+ "\'>");

								out.println("</td></tr>");
								out.println("<tr><td>Linked URL</td>");
								out.println("<td>");

								out.println("<input type=text name=linked_url size =150 maxsize=200");
								out.println("value=''>");

								out.println("</td></tr>");

								out.println("<tr><td></td>");
								out.println("<td>");
								out.println("<textarea rows=\"5\" cols=\"120\" name=\"file_containt\">");
								out.println("");
								out.println("</textarea>");
								out.println("</td></tr>");

								out.println("<input type=hidden name=aid value=3>");

								out.println("<input type=hidden name=submit_thread value="
										+ session.getAttribute(vcsid) + ">");

								out.println("<input type=hidden name=avcsid value=3>");
								out.println("<input type=hidden name=pid value="
										+ pid + ">");
								out.println("<input type=hidden name=position value='"
										+ position + "-0'>");
								out.println("<input type=hidden name=vcid value="
										+ vcid + ">");
								out.println("<input type=hidden name=vsid value="
										+ vsid + ">");
								out.println("<input type=hidden name=vcsid value="
										+ vcsid + ">");
								out.println("<tr><td></td>");
								out.println("<td>");
								out.println("<BR><input type=submit name=Add value=ADD>");
								out.println("</td></tr>");
								out.println("</table>");
								out.println("</form>");
							}
						} else {
							System.out
									.println("Main;;;CCCCCCCCCCCCCCCCCCCCCCCCCC");
							if (edit_thread != null
									&& edit_thread.equals("true")) {
								System.out
										.println("Main;;;DDDDDDDDDDDDDDDDDDDDDDDDDD");
								ForumThread forumthread = getSingleForumThread(
										request.getParameter("vsid"),
										request.getParameter("vcsid"));
								out.println("AAAAAAAAAAAAAAAAA["
										+ forumthread.getTitle() + "]");
								/**
								 * This is the form to Edit Thread
								 */
								out.println("<form action=>");
								out.println("<table bgcolor=#DEDEDE width=90%>");
								out.println("<tr><td colspan=2 bgcolor=#A596CB><b>Editing "
										+ forumthread.getTitle()
										+ "</d></td></tr>");
								out.println("<tr><td>Title</td>");
								out.println("<td>");

								out.println("<input type=text name=file_title size =150 maxsize=200");
								out.println("value=\'" + forumthread.getTitle()
										+ "\'>");

								out.println("</td></tr>");
								out.println("<tr><td>Linked URL</td>");
								out.println("<td>");

								out.println("<input type=text name=linked_url size =150 maxsize=200");
								out.println("value='"
										+ forumthread.getLinked_url() + "'>");

								out.println("</td></tr>");

								out.println("<tr><td></td>");
								out.println("<td>");
								out.println("<textarea rows=\"5\" cols=\"120\" name=\"file_containt\">");
								out.println(forumthread.getMessage());
								out.println("</textarea>");
								out.println("</td></tr>");

								out.println("<input type=hidden name=aid value=3>");

								out.println("<input type=hidden name=submit_thread value="
										+ session.getAttribute(vcsid) + ">");

								out.println("<input type=hidden name=avcsid value=3>");
								out.println("<input type=hidden name=pid value="
										+ pid + ">");
								out.println("<input type=hidden name=position value='"
										+ position + "'>");
								out.println("<input type=hidden name=vcid value="
										+ vcid + ">");
								out.println("<input type=hidden name=vsid value="
										+ vsid + ">");
								out.println("<input type=hidden name=vcsid value="
										+ vcsid + ">");
								out.println("<tr><td></td>");
								out.println("<td>");
								out.println("<BR><input type=submit name=update_thread value=Update>");
								out.println("</td></tr>");
								out.println("</table>");
								out.println("</form>");
							} else {
								System.out
										.println("Main;;;EEEEEEEEEEEEEEEEEEEEEEEEE");

								/**
								 * Save new post or reply
								 */
								if (request.getParameter("update_thread") != null) {
									//out.println("<h3>updaet thread </h3>");

									ForumThread frmthrd = new ForumThread();
									frmthrd.setId(Integer.parseInt(request.getParameter("vsid")));
									frmthrd.setBoard_id(request.getParameter("vcsid"));
									frmthrd.setParent_id(Integer.parseInt(request.getParameter("pid")));
									frmthrd.setTitle(request.getParameter("file_title"));
									frmthrd.setPosition(request.getParameter("position"));
									frmthrd.setMessage(request.getParameter("file_containt"));
									frmthrd.setLinked_url(request.getParameter("linked_url"));
									frmthrd.setType(""+request.getParameter("type"));
									frmthrd.setOwner(request.getRemoteUser());
									frmthrd.setDate(new java.sql.Date(System.currentTimeMillis()));
									
									updateForumThreadByUser(frmthrd);
								} else {
									Session hsession = null;
									Transaction transaction = null;

									try {
										hsession = HibernateUtil
												.getSessionFactory()
												.openSession();

										ForumThread frmthrd = new ForumThread();
										frmthrd.setBoard_id(vcsid);
										frmthrd.setTitle(request
												.getParameter("file_title"));

										frmthrd.setOwner(request
												.getRemoteUser());

										frmthrd.setPosition(position);

										frmthrd.setParent_id(Integer
												.parseInt(pid));
										frmthrd.setDate(new java.sql.Date(
												System.currentTimeMillis()));

										/*
										 * TextToHtml tthm = new TextToHtml();
										 * frmthrd.setMessage(tthm.textToHtml(
										 * request
										 * .getParameter("file_containt"))
										 * .toString());
										 */

										frmthrd.setMessage(request
												.getParameter("file_containt")
												.toString());

										frmthrd.setLinked_url(request
												.getParameter("linked_url"));

										hsession = HibernateUtil
												.getSessionFactory()
												.openSession();
										transaction = hsession
												.beginTransaction();

										System.out
												.println("<BR><BR>>>>>>>>>>>>ForumThread ["
														+ hsession
																.save(frmthrd)
														+ "] Saved. Parent_id="
														+ pid);
										transaction.commit();

									} catch (HibernateException e) {
										out.println("<H3><BR>Save Message Error.</H3>"
												+ e + "");
										transaction.rollback();
										e.printStackTrace();
									} catch (Exception e) {
										out.println("Save Message Error.<BR>"
												+ e + "<BR><BR>");
									}

									finally {
										session.setAttribute(vcsid, null);
										hsession.close();
									}
								}
							}
						}
					}
				}
			}

			/**
			 * This secitoin for creating subject related
			 */

			String top_main = "" + request.getAttribute("top_main");
			if (top_main != null) {
				if (top_main.equals("add_category")) {
					out.println("<BR><BR><BR><form action=>");
					out.println("<table><tr>");
					out.println("<td>Category Name:</td><td><input type=text name=category_name size =20 maxsize=20 value='"
							+ request.getParameter("new_category") + "'></td>");
					out.println("</tr>");
					out.println("<tr>");
					out.println("<td>Description:</td><td><input type=text name=category_description size =100 maxsize=200></td>");
					out.println("</tr>");
					out.println("<tr><td></td><td></td></tr>");
					out.println("<tr><td></td><td><input type=submit name=add_category value='Add Category'></td></tr>");
					out.println("</table>");
					out.println("<input type=hidden name=add_category_form_id value="
							+ session.getAttribute("ADD_CATEGORY_FORM_ID")
							+ ">");
					out.println("</form>");
				}
				if (top_main.equals("add_category_ok")) {
					out.println("<BR><BR><BR>");
					out.println("<table>");
					out.println("<tr><td></td><td>Added .......OK</td></tr>");
					out.println("<tr><td>Category Name:</td><td>"
							+ request.getParameter("category_name") + "</td>");
					out.println("</tr>");
					out.println("<tr>");
					out.println("<td>Description:</td><td>"
							+ request.getParameter("category_description")
							+ "</td>");
					out.println("</tr>");
					out.println("<tr><td></td><td></td></tr>");
					out.println("<tr><td></td><td></td></tr>");
					out.println("</table>");
				}

				if (top_main.equals("add_category_over_limit")) {
					out.println("<BR><BR><BR>");
					out.println("<table>");
					out.println("<tr><td></td><td>You have over limited categories. Not add</td></tr>");
					out.println("<tr><td>Category Name:</td><td>"
							+ request.getParameter("new_category") + "</td>");
					out.println("</tr>");
					out.println("<tr>");
					out.println("<td>Description:</td><td>"
							+ request.getParameter("category_description")
							+ "</td>");
					out.println("</tr>");
					out.println("<tr><td></td><td></td></tr>");
					out.println("<tr><td></td><td></td></tr>");
					out.println("</table>");
				}
			}

			String vleft_main = "" + request.getAttribute("vleft_main");
			if (vleft_main != null) {
				if (vleft_main.equals("add_subject")) {
					out.println("<BR><BR><BR><form action=>");
					out.println("<table><tr><td>Category Name:</td><td>"
							+ request.getParameter("vcname") + "["
							+ request.getParameter("vcid") + "]</td></tr>");
					out.println("<tr><td>Subject Name:</td><td><input type=text name=subject_name size =20 maxsize=20 value='"
							+ request.getParameter("new_subject") + "'></td>");
					out.println("</tr>");
					out.println("<tr>");
					out.println("<td>Description:</td><td><input type=text name=subject_description size =100 maxsize=200></td>");
					out.println("</tr>");
					out.println("<tr><td></td><td></td></tr>");
					out.println("<tr><td></td><td><input type=submit name=add_subject value='Add Subject'></td></tr>");
					out.println("</table>");
					out.println("<input type=hidden name=add_subject_form_id value="
							+ session.getAttribute("ADD_SUBJECT_FORM_ID") + ">");
					out.println("<input type=hidden name=vcname value="
							+ request.getParameter("vcname") + ">");
					out.println("<input type=hidden name=vcid value="
							+ request.getParameter("vcid") + ">");
					out.println("</form>");
				}

				if (vleft_main.equals("add_subject_ok")) {
					out.println("<BR><BR><BR>");
					out.println("<table>");
					out.println("<tr><td></td><td>Added .......OK</td></tr>");
					out.println("<tr><td>Subject Name:</td><td>"
							+ request.getParameter("subject_name") + "</td>");
					out.println("</tr>");
					out.println("<tr>");
					out.println("<td>Description:</td><td>"
							+ request.getParameter("subject_description")
							+ "</td>");
					out.println("</tr>");
					out.println("<tr><td></td><td></td></tr>");
					out.println("<tr><td></td><td></td></tr>");
					out.println("</table>");
				}
				if (vleft_main.equals("add_subject_over_limit")) {
					out.println("<BR><BR><BR>");
					out.println("<table>");
					out.println("<tr><td></td><td>You have over limited categories. Not add</td></tr>");
					out.println("<tr><td>Category Name:</td><td>"
							+ request.getParameter("new_category") + "</td>");
					out.println("</tr>");
					out.println("<tr>");
					out.println("<td>Description:</td><td>"
							+ request.getParameter("category_description")
							+ "</td>");
					out.println("</tr>");
					out.println("<tr><td></td><td></td></tr>");
					out.println("<tr><td></td><td></td></tr>");
					out.println("</table>");
				}
			}

			/**
			 * This secitoin display threads
			 */

			Session hsession = null;
			Transaction transaction = null;

			try {
				if (vcsid != null) {
					hsession = HibernateUtil.getSessionFactory().openSession();
					Criteria criteria = hsession
							.createCriteria(ForumThread.class);
					List<ForumThread> flist = new ArrayList<ForumThread>();
					flist = criteria.add(Restrictions.eq("board_id", vcsid))
							.list();
					System.out.println(">>>>>>>>>>>>>>>>>>board_id=" + vcsid);
					// flist = criteria.list();
					// Collections.sort(flist);
					Iterator<ForumThread> its = flist.iterator();
					String apace = null;
					while (its.hasNext()) {
						ForumThread forthr = (ForumThread) its.next();

						if (forthr.getParent_id() == 0) {
							out.println("<table><tr>");
							out.println("<td>&spades;");
							// out.println("["+forthr.getPosition()+"]");
							out.println("</td>");
							out.println("<td>");
							// out.println("[" + forthr.getId()+"]");
							out.println("</td>");
							out.println("<td>");
							// out.println("[" + forthr.getParent_id()+"]");
							out.println("</td>");
							out.println("<td>");
							out.println("<a href=?vcid="
									+ vcsid.substring(0, vcsid.indexOf('-'))
									+ "&vcsid=" + vcsid + "&vsid="
									+ forthr.getId() + "&avcsid=3&pid="
									+ forthr.getId() + "&position="
									+ forthr.getPosition() + ">"
									+ forthr.getTitle() + "</a>");
							out.println("</td>");
							out.println("<td>");
							out.println("By----&nbsp;&nbsp;<I>"
									+ forthr.getOwner());
							out.println("</I></td>");
							out.println("<td>--" + forthr.getDate() + "</td>"
							// + "<td>"
							// + "<a href=?vcid="
							// + vcsid.substring(0, vcsid.indexOf('-'))
							// + "&vcsid=" + vcsid + "&vsid="
							// + forthr.getId() + "&avcsid=3&pid="
							// + forthr.getId() + "&position="
							// + forthr.getPosition() + ">" + "Edit</a>"
							// + "</td>"
									+ "</tr>");
							// out.println("<tr><td colspan=5>" +
							// forthr.getMessage()+ "</td></tr>");
							out.println("</table>");
							out.println(showAllMyThreads(flist, forthr.getId(),
									vcsid).toString());
						}
					}
				}
			} catch (HibernateException e) {
				System.out.println("Access Thread Error:" + e);
				transaction.rollback();
			}

			if (true && request.getRemoteUser() != null
					&& request.getRemoteUser().equals("wli")) {
				out.println("<table border=1><tr><td colspan=2  bgcolor=#EFEFEF>");
				RequestDispatcher dispatcher = request
						.getRequestDispatcher("debug");
				dispatcher.include(request, response);
				out.println("</td></tr></table>");
			}
		} catch (Exception e) {
			System.out.println(e);
		}
	}

	private int updateForumThreadByUser(ForumThread frmthrd) {
		Session hsession = null;
		Transaction transaction = null;

		try {
			hsession = HibernateUtil.getSessionFactory().openSession();
		
			System.out.println("\n\n\n\n===========================================\n\nID=" + frmthrd.getId());
			System.out.println("PID=" + frmthrd.getParent_id());
			System.out.println("BID=" + frmthrd.getBoard_id());
			System.out.println("TITLE=" + frmthrd.getTitle());
			System.out.println("POSITION=" + frmthrd.getPosition());
			System.out.println("URL=" + frmthrd.getLinked_url());
			System.out.println("MESSAGE=" + frmthrd.getMessage());
			System.out.println("OWNER=" + frmthrd.getOwner());
			System.out.println("TYPE+" + frmthrd.getType());

			hsession = HibernateUtil.getSessionFactory().openSession();
			transaction = hsession.beginTransaction();
			hsession.update(frmthrd);
			transaction.commit();
			return 1;
		} catch (HibernateException e) {
			transaction.rollback();
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			//transaction.commit();
			hsession.close();
		}
		return -1;
	}

	private int updateForumThread(String vcid, String vsid, String vcsid,
			String file_title, String position, String file_containt,
			String linked_url, String owner, String type) {
		Session hsession = null;
		Transaction transaction = null;

		try {
			hsession = HibernateUtil.getSessionFactory().openSession();
			ForumThread frmthrd = new ForumThread();
			frmthrd.setId(Integer.parseInt(vsid));
			frmthrd.setParent_id(Integer.parseInt(vcid));
			frmthrd.setBoard_id(vcsid);
			frmthrd.setTitle(file_title);
			frmthrd.setPosition(position);
			frmthrd.setDate(new java.sql.Date(System.currentTimeMillis()));
			frmthrd.setMessage(file_containt);
			frmthrd.setLinked_url(linked_url);
			frmthrd.setOwner(owner);
			frmthrd.setType(type);

			System.out.println("ID=" + frmthrd.getId());
			System.out.println("PID=" + frmthrd.getParent_id());
			System.out.println("BID=" + frmthrd.getBoard_id());
			System.out.println("TITLE=" + frmthrd.getTitle());
			System.out.println("POSITION=" + frmthrd.getPosition());
			System.out.println("URL=" + frmthrd.getLinked_url());
			System.out.println("MESSAGE=" + frmthrd.getMessage());
			System.out.println("OWNER=" + frmthrd.getOwner());
			System.out.println("TYPE+" + frmthrd.getType());

			/*
			 * frmthrd.setId(76); frmthrd.setParent_id(0);
			 * frmthrd.setBoard_id("2001-11"); frmthrd.setTitle("TITLE-TITLE");
			 * frmthrd.setPosition("0-0"); frmthrd.setDate(new
			 * java.sql.Date(System.currentTimeMillis())); frmthrd.setMessage(
			 * "asdfsdfsd af asdlf ksdjaflasdjfljsdkl jfasdkfjasdkl fsdfklsd fsd"
			 * ); frmthrd.setLinked_url("http://google.com");
			 */

			hsession = HibernateUtil.getSessionFactory().openSession();
			transaction = hsession.beginTransaction();
			hsession.update(frmthrd);
			transaction.commit();
			return 1;
		} catch (HibernateException e) {
			transaction.rollback();
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			hsession.close();
		}
		return -1;
	}

	private StringBuffer getSingleThreadTitle(String thid) {
		if (thid == null) {
			thid = "0";
		}
		StringBuffer sbf = new StringBuffer();
		Session hsession = null;
		Transaction transaction = null;
		try {

			hsession = HibernateUtil.getSessionFactory().openSession();
			Criteria criteria = hsession.createCriteria(ForumThread.class);
			List<ForumThread> flist = new ArrayList<ForumThread>();
			flist = criteria.add(Restrictions.eq("id", Integer.parseInt(thid)))
					.list();

			Iterator<ForumThread> its = flist.iterator();
			String apace = null;
			while (its.hasNext()) {
				ForumThread forthr = (ForumThread) its.next();
				if (forthr.getId() == (Integer.parseInt(thid))) {
					sbf.append(forthr.getTitle());
				}
			}
		} catch (HibernateException e) {
			System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
					+ e);
		} finally {
			hsession.close();
		}

		return sbf;
	}

	private ForumThread getSingleForumThread(String thid, String board_id) {
		ForumThread fthread;

		fthread = new ForumThread();
		fthread.setTitle("Title");
		fthread.setMessage("Message");
		fthread.setOwner("System");
		fthread.setType("Public");
		fthread.setDate(new Date());

		Session hsession = null;
		Transaction transaction = null;
		try {

			hsession = HibernateUtil.getSessionFactory().openSession();
			Criteria criteria = hsession.createCriteria(ForumThread.class);
			List<ForumThread> flist = new ArrayList<ForumThread>();
			flist = criteria.add(Restrictions.eq("id", Integer.parseInt(thid)))
					.add(Restrictions.eq("board_id", board_id)).list();

			Iterator<ForumThread> its = flist.iterator();
			String apace = null;
			while (its.hasNext()) {
				fthread = (ForumThread) its.next();
				if (fthread.getId() == (Integer.parseInt(thid))) {
					return fthread;
				}
			}
		} catch (HibernateException e) {
			System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
					+ e);
		} finally {
			hsession.close();
		}

		return fthread;
	}

	private StringBuffer getSingleThread(String thid) {
		if (thid == null) {
			thid = "0";
		}
		StringBuffer sbf = new StringBuffer();
		Session hsession = null;
		Transaction transaction = null;
		try {

			hsession = HibernateUtil.getSessionFactory().openSession();
			Criteria criteria = hsession.createCriteria(ForumThread.class);
			List<ForumThread> flist = new ArrayList<ForumThread>();
			flist = criteria.add(Restrictions.eq("id", Integer.parseInt(thid)))
					.list();

			Iterator<ForumThread> its = flist.iterator();
			String apace = null;
			while (its.hasNext()) {
				ForumThread forthr = (ForumThread) its.next();
				if (forthr.getId() == (Integer.parseInt(thid))) {
					sbf.append(forthr.getMessage());
				}
			}
		} catch (HibernateException e) {
			// transaction.rollback();
			System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
					+ e);
		} finally {
			hsession.close();
		}

		return sbf;
	}

	private StringBuffer showAllMyThreads(List<ForumThread> list,
			int thread_id, String boardid) {
		StringBuffer sbf = new StringBuffer();
		Iterator<ForumThread> it = list.iterator();
		ForumThread forthr;

		String path_to_show = null;
		String temp;
		while (it.hasNext()) {
			forthr = it.next();
			if (forthr.getParent_id() == thread_id
					&& forthr.getBoard_id().equals(boardid)) {

				sbf.append("<table><tr>");
				sbf.append("<td>");
				sbf.append((forthr.getPosition().replaceAll("0", "&nbsp;"))
						.replaceAll("-", "&nbsp;"));
				sbf.append("&diams;</td>");
				sbf.append("<td>");
				// sbf.append("[" + forthr.getId()+"]");
				sbf.append("</td>");
				sbf.append("<td>");
				// sbf.append("[" + forthr.getParent_id()+"]");
				sbf.append("</td>");
				sbf.append("<td>");
				temp = forthr.getBoard_id();
				if (temp != null && temp.indexOf('-') != -1) {
					temp = temp.substring(0, temp.indexOf('-'));
				}
				sbf.append("<a href=?vcid=" + temp + "&vcsid="
						+ forthr.getBoard_id() + "&vsid=" + forthr.getId()
						+ "&avcsid=3&pid=" + forthr.getParent_id()
						+ "&position=" + forthr.getPosition() + ">"
						+ forthr.getTitle() + "</a>");
				sbf.append("</td>");
				sbf.append("<td>");
				sbf.append("By:&nbsp;&nbsp;<i>" + forthr.getOwner());
				sbf.append("</I></td>");
				sbf.append("<td>--"
						+ (forthr.getDate().toString()).substring(0, 10)
						+ "</td></tr>");
				// sbf.append("<tr><td colspan=5>" + forthr.getMessage()+
				// "</td></tr>");
				sbf.append("</table>");

				sbf.append(showAllMyThreads(list, forthr.getId(), boardid));
			}
		}
		return sbf;
	}

	private List<Category> getCategoryList(String username) {
		Category cate;
		List<Category> clist;
		Session hsession = null;
		Transaction transaction = null;
		try {

			hsession = HibernateUtil.getSessionFactory().openSession();
			Criteria criteria = hsession.createCriteria(Category.class);
			clist = new ArrayList<Category>();
			clist = criteria.add(Restrictions.eq("owner", username)).list();
			return clist;
		} catch (HibernateException e) {
			e.printStackTrace();
		} finally {
			hsession.close();
		}

		return null;
	}

	private boolean hasSubject(int category_id) {
		Session hsession = null;
		Transaction transaction = null;
		Subject subj = null;
		List<Subject> clist = new ArrayList<Subject>();
		try {

			hsession = HibernateUtil.getSessionFactory().openSession();
			Criteria criteria = hsession.createCriteria(Subject.class);
			clist = criteria.add(Restrictions.eq("categoryId", category_id))
					.list();

			if (clist != null && clist.size() > 0) {
				return true;
			}
		} catch (HibernateException e) {
			e.printStackTrace();
		}
		return false;
	}
}
